package com.netty.chapter04;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class Client {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("localhost", 8080));
//        // sync 异步阻塞，直到nio建立连接完毕
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        channel.writeAndFlush("你好");
//        System.out.println("");

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            // nio连接建立好后会执行该方法
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                log.info("异步连接建立");
                new Thread(()->{
                    Scanner scanner=new Scanner(System.in);
                    while (true){
                        String line=scanner.nextLine();
                        if(line.equals("q")){
                            channel.close();
                            // 关闭连接
                            log.info("开始关闭连接...");
                            break;
                        }
                        channel.writeAndFlush(line);
                    }
                }).start();
                ChannelFuture closeFuture = channel.closeFuture();
                closeFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        group.shutdownGracefully();// 优雅的关闭
                        log.info("处理关闭后的操作");
                    }
                });
            }
        });

    }
}
